use std::fmt::{Display, Formatter};
use std::sync::{Arc};

use dashmap::DashMap;

#[derive(Debug, Clone)]
pub struct MetricsDashMap {
    pub data: Arc<DashMap<String, i64>>,
}

impl MetricsDashMap {
    pub fn new() -> Self {
        MetricsDashMap {
            data: Arc::new(DashMap::new()),
        }
    }

    pub fn inc(&self, key: &str) {
        // let mut temp = self.data.unwrap();
        let mut counter = self.data.entry(key.to_string()).or_insert(0);  // 根据key找 entry , 如果找不到， 设置value 为 0

        *counter += 1;
        // self.data
    }


    pub fn desc(&mut self, key: &str) {
        // let mut temp = self.data.write().unwrap();
        let mut counter = self.data.entry(key.to_string()).or_insert(0);
        *counter -= 1;
    }
}


impl Display for MetricsDashMap {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let mut res = String::new();
        for entry in self.data.iter() {
            res.push_str(&format!("{}: {}\n", entry.key(), entry.value()));
        }
        write!(f, "{}", res)
    }
}